package com.ccom.gateway.filter;

import com.ccom.gateway.properties.AuthProperty;
import com.ccom.gateway.provider.AuthProvider;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 接口请求过滤
 * @Author: zjj
 * @Date: 2021/12/21
 */
@Slf4j
@Component
@EnableConfigurationProperties(AuthProperty.class)
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {

    private final AuthProperty authProperty;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (isSkip(path)) {
            return chain.filter(exchange);
        }
        return null;
    }

    private boolean isSkip(String path) {
        return !authProperty.getEnable() || AuthProvider.getDefaultSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path))
                || authProperty.getSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
